package com.heima.wemedia.interceptor;

import cn.hutool.http.HttpStatus;
import com.alibaba.fastjson.JSON;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.WmThreadLocalUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//自媒体拦截器
@Component
public class WmTokenInterceptor extends HandlerInterceptorAdapter {
    //在访问资源前执行
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //从请求头里取出userid,放入本地线程ThreadLocal中
        String userId = request.getHeader("userId");
        if (StringUtils.isNoneBlank(userId)) {
            WmThreadLocalUtil.set(Long.valueOf(userId));
            //放行
            return super.preHandle(request, response, handler);
        }
        //如果请求头里没有userid说明用户未登录,不允许直接访问后台资源
        response.setCharacterEncoding("Utf-8");
        response.setStatus(HttpStatus.HTTP_UNAUTHORIZED);//401
        response.getWriter().write(JSON.toJSONString(ResponseResult.errorResult(AppHttpCodeEnum.NO_OPERATOR_AUTH)));
        return false;
    }

    //访问资源后执行
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        WmThreadLocalUtil.remove();
        super.postHandle(request, response, handler, modelAndView);
    }

    //

}
